package com.mxdx.edu.util;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class RedisUtil {

	@Resource
	private RedisTemplate<String, Object> redisTemplate;

	public void set(String key, Object value) {
		ValueOperations<String, Object> vo = redisTemplate.opsForValue();
		vo.set(key, value);
	}

	public void set(String key, Object value, long timeOut) {
		ValueOperations<String, Object> vo = redisTemplate.opsForValue();
		vo.set(key, value, timeOut, TimeUnit.SECONDS);
	}

	public Object get(String key) {
		if (key == null) {
			return null;
		}
		ValueOperations<String, Object> vo = redisTemplate.opsForValue();
		return vo.get(key);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void setEx(final String key, final String value, final long liveTime) {
		redisTemplate.execute(new RedisCallback() {
			public Long doInRedis(RedisConnection connection)
					throws DataAccessException {
				connection.setEx(key.getBytes(), liveTime, value.getBytes());
				return 1L;
			}
		});
	}

	public void delete(String key) {
		if (key != null) {
			redisTemplate.delete(key);
		}
	}
}
